package org.fixies.spreadsheet;

import java.util.*;

import static org.fixies.utils.StringUtils.concat;
import static org.fixies.utils.StringUtils.toCsv;

/**
 * 行
 *
 * @author Kawasaki
 */
public class Row implements Iterable<Cell>, Element {

    private final List<Cell> cells_;

    private Unit parent_;

    private final int id_;

    public Row(String[] cellData, Unit parent, int rowIndex) {
        this(Arrays.asList(cellData), parent, rowIndex);
    }
    
    void setParent(Unit parent) {
        if (parent_ != null) {
            throw new IllegalStateException("already has parent.");
        }
        parent_ = parent;
    }
    public Row(List<String> cellData, Unit parent, int rowIndex) {
        parent_ = parent;
        id_ = rowIndex;

        List<Cell> cells = new ArrayList<Cell>(cellData.size());
        int i = 0;
        for (String s : cellData) {
            Cell c = new Cell(s, this, i++);
            cells.add(c);
        }
        cells_ = Collections.unmodifiableList(cells);
    }

    public Iterator<Cell> iterator() {
        return cells_.iterator();
    }

    public String[] toStringArray() {
        int size = cells_.size();
        List<String> l = new ArrayList<String>(size);
        for (Cell cell : cells_)
            l.add(cell.asString());
        return l.toArray(new String[size]);
    }

    @Override
    public String toString() {
        return concat("[", toCsv(toStringArray()), "]");
    }

    public Cell get(int index) {
        if (size() < index) {
            // TODO
            return null;
        }
        return cells_.get(index);
    }

    public int size() {
        return cells_.size();
    }

    public String getId() {
        return String.valueOf(id_);
    }

    public String getOrigin() {
        return parent_.getOrigin() + ", Row=[" + id_ + "]";
    }

    public boolean isEmpty() {
        for (Cell c : cells_) {
            if (!c.isEmpty()) return false;
        }
        return true;
    }
}
